package com.usbserial;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.hardware.usb.UsbManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.itianshan.wheel.R;
import com.itianshan.wheel.WheelView;

import cn.wch.ch34xuartdriver.CH34xUARTDriver;

public class UsbWheelActivity extends Activity {

    public static final String TAG = "cn.wch.wchusbdriver";
    private static final String ACTION_USB_PERMISSION = "cn.wch.wchusbdriver.USB_PERMISSION";

    public readThread handlerThread;
    protected final Object ThreadLock = new Object();
    private EditText readText;
    private EditText writeText;
    private Spinner baudSpinner;
    private Spinner stopSpinner;
    private Spinner dataSpinner;
    private Spinner paritySpinner;
    private Spinner flowSpinner;
    private boolean isOpen;
    private Handler handler;
    private int retval;
    private UsbWheelActivity activity;

    //private Button writeButton, configButton, openButton, clearButton;

    public byte[] writeBuffer;
    public byte[] readBuffer;
    public int actualNumBytes;

    public int numBytes;
    public byte count;
    public int status;
    public byte writeIndex = 0;
    public byte readIndex = 0;

    public int baudRate = 115200;
    public byte baudRate_byte;
    public byte stopBit=1;
    public byte dataBit=8;
    public byte parity=3;  //None:0;Odd:1,Even:2,Mark:3,Space:4  校验位取值
    public byte flowControl;

    public boolean isConfiged = false;
    public boolean READ_ENABLE = false;
    public SharedPreferences sharePrefSettings;
    public String act_string;
    public static CH34xUARTDriver driver;// 需要将CH34x的驱动类写在APP类下面，使得帮助类的生命周期与整个应用程序的生命周期是相同的
    private TextView mConnectionState;
    private TextView send_count;
    private WheelView wheelView_01;
    private TextView textView_01;
    private WheelView wheelView_02;
    private TextView textView_02;
    private TextView sbValues;
    private int speed;
    private int direction;
    private int tx_count=0;
    private  boolean mConnected=false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
        //WindowManager.LayoutParams.FLAG_FULLSCREEN);//设置成全屏模式
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);//强制为横屏
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.wheel_main);
        this.driver = new CH34xUARTDriver(
                (UsbManager) getSystemService(Context.USB_SERVICE), this,
                ACTION_USB_PERMISSION);
        initUI();
        if (!this.driver.UsbFeatureSupported())// 判断系统是否支持USB HOST
        {
            Dialog dialog = new AlertDialog.Builder(UsbWheelActivity.this)
                    .setTitle("提示")
                    .setMessage("您的手机不支持USB HOST，请更换其他手机再试！")
                    .setPositiveButton("确认",
                            new DialogInterface.OnClickListener() {

                                @Override
                                public void onClick(DialogInterface arg0,
                                                    int arg1) {
                                    System.exit(0);
                                }
                            }).create();
            dialog.setCanceledOnTouchOutside(false);
            dialog.show();
        }
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);// 保持常亮的屏幕的状态
        writeBuffer = new byte[512];
        readBuffer = new byte[512];
        isOpen = false;
        //configButton.setEnabled(false);
        //writeButton.setEnabled(false);
        activity = this;
        connect();
        setting();


        wheelView_01.setOnWheelViewMoveListener(
                new WheelView.OnWheelViewMoveListener() {
                    @Override
                    public void onValueChanged(int angle, int distance) {
                        textView_01.setText("角度：" + angle + "\n" +	"距离：" + distance);
                        if(angle<-115 && -180<angle){
                            angle = -(180+angle);
                        }
                        if (115<angle && angle<180){
                            angle = 180-angle;
                        }
                        if(!(angle>-65 && angle <65)){
                            angle = direction;
                        }
                        String dir = angle==0?"":(angle>0?"右":"左");
                        textView_01.setText("方向：" +dir+ Math.abs(angle) + "\n");

                        if( isOpen && direction!=angle)
                        {
                            send_count.setText("发送数据："+tx_count);
                            send("{\"dir\":"+String.valueOf(angle)+"}\r\n");
                        }else{
                            //Toast.makeText(UsbWheelActivity.this, "Deleted Successfully!", Toast.LENGTH_LONG).show();
                            //Toast toast = Toast.makeText(UsbWheelActivity.this, "设备没有连接！", Toast.LENGTH_SHORT);
                            // toast.show();
                        }
                        direction = angle;
                    }
                }, 100L);
        wheelView_02.setOnWheelViewMoveListener(
                new WheelView.OnWheelViewMoveListener() {
                    @Override
                    public void onValueChanged(int angle, int distance) {
                        //textView_02.setText("角度：" + angle + "\n" +	"距离：" + distance);
                        if(!(angle>-95 && angle <95)){
                            distance = -distance/10;
                        }
                        textView_02.setText("速度：" + distance+"%"+(distance==0?"":(distance>0?"前进":"倒车")));
                        if( isOpen && speed!=distance)
                        {
                            send_count.setText("发送数据："+tx_count);
                            send("{\"spe\":"+String.valueOf(distance)+"}\r\n");
                        }else{
                            //Toast.makeText(UsbWheelActivity.this, "Deleted Successfully!", Toast.LENGTH_LONG).show();
                            //Toast toast = Toast.makeText(UsbWheelActivity.this, "设备没有连接！", Toast.LENGTH_SHORT);
                            //toast.show();
                        }
                        speed = distance;
                    }
                }, 100L);

        //打开流程主要步骤为ResumeUsbList，UartInit
        /*
        openButton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                connect();
            }
        });

        configButton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                setting();
            }
        });
        writeButton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                byte[] to_send = toByteArray(writeText.getText().toString());		//以16进制发送
//				byte[] to_send = toByteArray2(writeText.getText().toString());		//以字符串方式发送
                int retval = UsbWheelTestActivity.driver.WriteData(to_send, to_send.length);//写数据，第一个参数为需要发送的字节数组，第二个参数为需要发送的字节长度，返回实际发送的字节长度
                if (retval < 0)
                    Toast.makeText(UsbWheelTestActivity.this, "Write failed!",
                            Toast.LENGTH_SHORT).show();
            }
        });

         */

        handler = new Handler() {
            public void handleMessage(Message msg) {
                System.out.print(msg);
                //textView_01.append((String) msg.obj);
            }
        };

    }
    private void setting(){
        if (UsbWheelActivity.driver.SetConfig(baudRate, dataBit, stopBit, parity,//配置串口波特率，函数说明可参照编程手册
                flowControl)) {
            Toast.makeText(UsbWheelActivity.this, "Config successfully",
                    Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(UsbWheelActivity.this, "Config failed!",
                    Toast.LENGTH_SHORT).show();
        }
    }
    private void connect(){
        if (!isOpen) {
            int retval = UsbWheelActivity.driver.ResumeUsbPermission();
            if (retval == 0) {
                //Resume usb device list
                retval = UsbWheelActivity.driver.ResumeUsbList();
                if (retval == -1)// ResumeUsbList方法用于枚举CH34X设备以及打开相关设备
                {
                    Toast.makeText(UsbWheelActivity.this, "Open failed!",
                            Toast.LENGTH_SHORT).show();
                    UsbWheelActivity.driver.CloseDevice();
                } else if (retval == 0){
                    if (UsbWheelActivity.driver.mDeviceConnection != null) {
                        if (!UsbWheelActivity.driver.UartInit()) {//对串口设备进行初始化操作
                            Toast.makeText(UsbWheelActivity.this, "Initialization failed!",
                                    Toast.LENGTH_SHORT).show();
                            return;
                        }
                        Toast.makeText(UsbWheelActivity.this, "Device opened",
                                Toast.LENGTH_SHORT).show();
                        isOpen = true;
                        //openButton.setText("Close");
                        //configButton.setEnabled(true);
                        //writeButton.setEnabled(true);
                        new readThread().start();//开启读线程读取串口接收的数据
                    } else {
                        Toast.makeText(UsbWheelActivity.this, "Open failed!",
                                Toast.LENGTH_SHORT).show();
                    }
                } else {
                    Toast.makeText(UsbWheelActivity.this, "未授权，清退出",
                            Toast.LENGTH_SHORT).show();

                }
            }
        } else {
            //openButton.setText("Open");
            //configButton.setEnabled(false);
            //writeButton.setEnabled(false);
            isOpen = false;
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            UsbWheelActivity.driver.CloseDevice();
        }
    }
    private void send(String str){
        System.out.print(str);
        byte[] to_send = toByteArray2(str);		//以16进制发送
//				byte[] to_send = toByteArray2(writeText.getText().toString());		//以字符串方式发送
        int retval = UsbWheelActivity.driver.WriteData(to_send, to_send.length);//写数据，第一个参数为需要发送的字节数组，第二个参数为需要发送的字节长度，返回实际发送的字节长度
        System.out.print(retval);
        System.out.print(str);
        if (retval < 0)
            Toast.makeText(UsbWheelActivity.this, "Write failed!",
                    Toast.LENGTH_SHORT).show();
    }
    @Override
    public void onResume() {
        super.onResume();
    }


    @Override
    public void onDestroy() {
        isOpen = false;
        this.driver.CloseDevice();
        super.onDestroy();
    }

    //处理界面
    private void initUI() {
        mConnectionState = (TextView) findViewById(R.id.connection_state);
        send_count = (TextView) findViewById(R.id.send_count);
        wheelView_01 = (WheelView) findViewById(R.id.wheelView_01);
        textView_01 = (TextView) findViewById(R.id.textView_01);
        wheelView_02 = (WheelView) findViewById(R.id.wheelView_02);
        textView_02 = (TextView) findViewById(R.id.textView_02);
        wheelView_01.setOnWheelViewMoveListener(
                new WheelView.OnWheelViewMoveListener() {
                    @Override
                    public void onValueChanged(int angle, int distance) {
                        textView_01.setText("角度：" + angle + "\n" +	"距离：" + distance);
                        if(angle<-115 && -180<angle){
                            angle = -(180+angle);
                        }
                        if (115<angle && angle<180){
                            angle = 180-angle;
                        }
                        if(!(angle>-65 && angle <65)){
                            angle = direction;
                        }
                        String dir = angle==0?"":(angle>0?"右":"左");
                        textView_01.setText("方向：" +dir+ Math.abs(angle) + "\n");

                        if( mConnected && direction!=angle)
                        {
                            send_count.setText("发送数据："+tx_count);
                            send("{\"dir\":"+String.valueOf(angle)+"}\r\n");
                        }else{
                            //Toast.makeText(UsbWheelActivity.this, "Deleted Successfully!", Toast.LENGTH_LONG).show();
                            //Toast toast = Toast.makeText(UsbWheelActivity.this, "设备没有连接！", Toast.LENGTH_SHORT);
                            // toast.show();
                        }
                        direction = angle;
                    }
                }, 100L);
        wheelView_02.setOnWheelViewMoveListener(
                new WheelView.OnWheelViewMoveListener() {
                    @Override
                    public void onValueChanged(int angle, int distance) {
                        //textView_02.setText("角度：" + angle + "\n" +	"距离：" + distance);
                        if(!(angle>-95 && angle <95)){
                            distance = -distance/10;
                        }
                        textView_02.setText("速度：" + distance+"%"+(distance==0?"":(distance>0?"前进":"倒车")));
                        if( mConnected && speed!=distance)
                        {
                            send_count.setText("发送数据："+tx_count);
                            send("{\"spe\":"+String.valueOf(distance)+"}\r\n");
                        }else{
                            //Toast.makeText(UsbWheelActivity.this, "Deleted Successfully!", Toast.LENGTH_LONG).show();
                            //Toast toast = Toast.makeText(UsbWheelActivity.this, "设备没有连接！", Toast.LENGTH_SHORT);
                            //toast.show();
                        }
                        speed = distance;
                    }
                }, 100L);
    }

    public class MyOnBaudSelectedListener implements OnItemSelectedListener {

        @Override
        public void onItemSelected(AdapterView<?> parent, View view,
                                   int position, long id) {
            baudRate = Integer.parseInt(parent.getItemAtPosition(position)
                    .toString());
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {

        }
    }

    public class MyOnStopSelectedListener implements OnItemSelectedListener {

        @Override
        public void onItemSelected(AdapterView<?> parent, View view,
                                   int position, long id) {
            stopBit = (byte) Integer.parseInt(parent
                    .getItemAtPosition(position).toString());
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {

        }

    }

    public class MyOnDataSelectedListener implements OnItemSelectedListener {

        @Override
        public void onItemSelected(AdapterView<?> parent, View view,
                                   int position, long id) {
            dataBit = (byte) Integer.parseInt(parent
                    .getItemAtPosition(position).toString());
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {

        }

    }

    public class MyOnParitySelectedListener implements OnItemSelectedListener {

        @Override
        public void onItemSelected(AdapterView<?> parent, View view,
                                   int position, long id) {
            String parityString = new String(parent.getItemAtPosition(position)
                    .toString());
            if (parityString.compareTo("None") == 0) {
                parity = 0;
            }

            if (parityString.compareTo("Odd") == 0) {
                parity = 1;
            }

            if (parityString.compareTo("Even") == 0) {
                parity = 2;
            }

            if (parityString.compareTo("Mark") == 0) {
                parity = 3;
            }

            if (parityString.compareTo("Space") == 0) {
                parity = 4;
            }
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {

        }

    }

    public class MyOnFlowSelectedListener implements OnItemSelectedListener {

        @Override
        public void onItemSelected(AdapterView<?> parent, View view,
                                   int position, long id) {
            String flowString = new String(parent.getItemAtPosition(position)
                    .toString());
            if (flowString.compareTo("None") == 0) {
                flowControl = 0;
            }

            if (flowString.compareTo("CTS/RTS") == 0) {
                flowControl = 1;
            }
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {

        }

    }

    private class readThread extends Thread {

        public void run() {

            byte[] buffer = new byte[4096];

            while (true) {

                Message msg = Message.obtain();
                if (!isOpen) {
                    break;
                }
                int length = UsbWheelActivity.driver.ReadData(buffer, 4096);
                if (length > 0) {
                    String recv = toHexString(buffer, length);		//以16进制输出
//					String recv = new String(buffer, 0, length);		//以字符串形式输出
                    msg.obj = recv;
                    handler.sendMessage(msg);
                }
            }
        }
    }

    /**
     * 将byte[]数组转化为String类型
     * @param arg
     *            需要转换的byte[]数组
     * @param length
     *            需要转换的数组长度
     * @return 转换后的String队形
     */
    private String toHexString(byte[] arg, int length) {
        String result = new String();
        if (arg != null) {
            for (int i = 0; i < length; i++) {
                result = result
                        + (Integer.toHexString(
                        arg[i] < 0 ? arg[i] + 256 : arg[i]).length() == 1 ? "0"
                        + Integer.toHexString(arg[i] < 0 ? arg[i] + 256
                        : arg[i])
                        : Integer.toHexString(arg[i] < 0 ? arg[i] + 256
                        : arg[i])) + " ";
            }
            return result;
        }
        return "";
    }

    /**
     * 将String转化为byte[]数组
     * @param arg
     *            需要转换的String对象
     * @return 转换后的byte[]数组
     */
    private byte[] toByteArray(String arg) {
        if (arg != null) {
            /* 1.先去除String中的' '，然后将String转换为char数组 */
            char[] NewArray = new char[1000];
            char[] array = arg.toCharArray();
            int length = 0;
            for (int i = 0; i < array.length; i++) {
                if (array[i] != ' ') {
                    NewArray[length] = array[i];
                    length++;
                }
            }
            /* 将char数组中的值转成一个实际的十进制数组 */
            int EvenLength = (length % 2 == 0) ? length : length + 1;
            if (EvenLength != 0) {
                int[] data = new int[EvenLength];
                data[EvenLength - 1] = 0;
                for (int i = 0; i < length; i++) {
                    if (NewArray[i] >= '0' && NewArray[i] <= '9') {
                        data[i] = NewArray[i] - '0';
                    } else if (NewArray[i] >= 'a' && NewArray[i] <= 'f') {
                        data[i] = NewArray[i] - 'a' + 10;
                    } else if (NewArray[i] >= 'A' && NewArray[i] <= 'F') {
                        data[i] = NewArray[i] - 'A' + 10;
                    }
                }
                /* 将 每个char的值每两个组成一个16进制数据 */
                byte[] byteArray = new byte[EvenLength / 2];
                for (int i = 0; i < EvenLength / 2; i++) {
                    byteArray[i] = (byte) (data[i * 2] * 16 + data[i * 2 + 1]);
                }
                return byteArray;
            }
        }
        return new byte[] {};
    }

    /**
     * 将String转化为byte[]数组
     * @param arg
     *            需要转换的String对象
     * @return 转换后的byte[]数组
     */
    private byte[] toByteArray2(String arg) {
        if (arg != null) {
            /* 1.先去除String中的' '，然后将String转换为char数组 */
            char[] NewArray = new char[1000];
            char[] array = arg.toCharArray();
            int length = 0;
            for (int i = 0; i < array.length; i++) {
                if (array[i] != ' ') {
                    NewArray[length] = array[i];
                    length++;
                }
            }

            byte[] byteArray = new byte[length];
            for (int i = 0; i < length; i++) {
                byteArray[i] = (byte)NewArray[i];
            }
            return byteArray;

        }
        return new byte[] {};
    }
}
